<template>
  <div id="list">
    <!-- 学生列表展示 -->
    <el-card shadow="hover">
      <!-- 添加学生信息 -->
      <el-form :inline="true" :model="formInline" ref="formInline" class="demo-form-inline" >                                                          
        <el-form-item label="姓名" >
          <el-input v-model="formInline.stuName" placeholder="姓名" clearable style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item label="年龄" >
          <el-input v-model="formInline.stuAge" placeholder="年龄" style="width: 100px;"></el-input>
        </el-form-item>
        <el-form-item label="成绩">
          <el-input v-model="formInline.claScore" placeholder="成绩" style="width: 100px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="selectByCondition" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" plain @click="resetSelectForm('formInline')" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" plain @click="addStudentDialogVisible=true" icon="el-icon-circle-plus-outline">添加学生</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" plain @click="deleteChecked" icon="el-icon-circle-plus-outline">删除选中</el-button>
        </el-form-item>
      </el-form>
      <el-table
          class="table"
          :data="studentList.filter(data => !search || data.stuName.toLowerCase().includes(search.toLowerCase()))"
          style="width: 100%"
          stripe="stripe"
          @selection-change="handleSelectionChange"
          :header-cell-style="{color:'#000'}">
        <el-table-column
            type="selection"
            width="80">
        </el-table-column>
        <el-table-column
            label="学号"
            prop="stuId"
            sortable>
        </el-table-column>
        <el-table-column
            label="姓名"
            prop="stuName">
        </el-table-column>
        <el-table-column
            label="年龄"
            prop="stuAge">
        </el-table-column>
        <el-table-column
            label="成绩"
            prop="claScore">
        </el-table-column>
        <el-table-column
            align="center">
          <template slot="header" slot-scope="scope">
            <el-input
                v-model="search"
                size="small"
                placeholder="输入关键字搜索"/>
          </template>
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
                :style="{color:'#000' }">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
<!--    分页-->
    <el-pagination
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <!-- 添加学生对话框 -->
    <el-dialog
      title="添加学生信息"
      :visible.sync="addStudentDialogVisible"
      width="40%"
      center
      :close-on-click-modal="false">
      <el-form :model="addMsgForm" :rules="rules" ref="addMsgForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="学生学号" prop="stuId" required>
          <el-input v-model="addMsgForm.stuId"></el-input>
        </el-form-item>        
        <el-form-item label="学生姓名" prop="stuName" required>
          <el-input v-model="addMsgForm.stuName"></el-input>
        </el-form-item>
        <el-form-item label="学生年龄" prop="stuAge" required>
          <el-input v-model.number="addMsgForm.stuAge"></el-input>
        </el-form-item>
        <el-form-item label="学生成绩" prop="claScore">
          <el-input v-model="addMsgForm.claScore"></el-input>
        </el-form-item>
        <el-form-item style="margin: 0 auto;">
          <el-button type="primary" @click="addStudent" plain>立即添加</el-button>
          <el-button type="warning" @click="resetForm('addMsgForm')" plain >重置</el-button>
          <el-button @click="addStudentDialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改学生成绩信息对话框 -->
    <my-dialog 
          :dialogTitle="dialogTitle" 
          :msgForm="updateMsgForm " 
          :dialogVisible="updateDialogVisible" 
          @formChange="formConfirm"
    ></my-dialog>

  </div>
</template>
<script>
import studentApi from '@/api/studentApi';
import MyDialog from '@/components/myDialog.vue';
export default {
  name: "stuList",
  components: {
    MyDialog
  },
  data() {
    let validateAge = (rule, value, callback) => {
      if (!Number.isInteger(value)) {
          callback(new Error('请输入整数字值'));
      }
      if (value<=0||value>120) {
        return callback(new Error('请注意年龄范围'));
      }
      else callback();
    };
    let validateScore = (rule, value, callback) => {
      if (isNaN(value)) {
          callback(new Error('请输入数字值'));
      }
      if (value<0||value>100) {
        return callback(new Error('请注意年龄范围'));
      }
      else callback();
    };
    return {
      msg: "这是list页面",
      search: '',  //表格中搜索框
      studentList: [],
      currentPage: 1,
      pageSize: 5,
      total: 20,
      addStudentDialogVisible:false,
      updateDialogVisible:false,
      dialogTitle:'',
      formInline: {
          stuId: '',
          stuName: '',
          stuAge:0,
          claScore:0
      },
      addMsgForm:{
        stuId:'',
        stuName:'',
        stuAge:0,
        claScore:0
      },
      updateMsgForm:{
        stuId:'',
        stuName:'',
        stuAge:0,
        claScore:0
      },
      deletedData:[],
      rules: {
          stuId: [
            { required: true, message: '请输入学生ID', trigger: 'blur' },
            { min: 8, max: 8, message: '长度为8字符', trigger: 'change' }
          ],
          stuName: [
            { required: true, message: '请输入学生姓名', trigger: 'blur' }
          ],
          stuAge: [
            { validator: validateAge ,trigger: 'blur'}
          ],
          claScore: [
            { validator: validateScore , trigger: 'change'}
          ]
          
      },
      
    }
  },
  created() {
    this.selectByPage();
  },
  mounted() {},
  methods: {
    //获取所有数据
    async getList() {
      let res = await studentApi.selectAll();
      console.log("查询所有数据")
      console.log(res)
      this.studentList = res.data.rows;
      this.total=parseInt(res.data.total);
    },
    // 分页函数
    async selectByPage(){
      let params={
        currentPage:this.currentPage,
        pageSize:this.pageSize
      }
      let res = await studentApi.selectByPage(params);
      console.log(res)
      this.studentList = res.data.rows;
      this.total=parseInt(res.data.total);
    },
    // 条件查询带分页
    async selectByCondition(){
      let res = await studentApi.selectByCondition(this.currentPage,this.pageSize, this.formInline);
      this.studentList=res.data.rows;
      this.total=parseInt(res.data.total);
      console.log(res)
    },
    //对话框添加学生
    addStudent(){
      this.$refs["addMsgForm"].validate(  async (valid) => {
        console.log(valid)
        if (valid) {
          console.log("添加学生")
          console.log(this.addMsgForm)
          let res =  await studentApi.addStudent(this.addMsgForm);
          console.log(res)
          if(res.data.code==200){
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
            this.addStudentDialogVisible=false;
            this.selectByPage();
          }else{
            this.$message({
              type: 'error',
              message: '添加失败!'
            });
          }
        } else {
          console.log('验证失败');
          return false;
        }
      });
      
    },
    //弹出的对话框中的确认函数
    async formConfirm(data){
      console.log(data)
      if(data.flag==1){
        // 添加学生
      }else if(data.flag==2){
        console.log("修改学生")
        let{id,...arg}=data.msg;
        console.log(arg)
        let res = await studentApi.updateStudent(data.msg.id,arg);
        console.log(res)
        if(res.data.code==200){
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.updateDialogVisible=false
          this.selectByPage();
        }else{
          this.$message({
            type: 'error',
            message: '修改失败!'
          });
        }
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.selectByPage();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.selectByPage();
    },
    //表格项编辑函数
    handleEdit(index, row) {
      this.dialogTitle="修改学生信息"
      this.updateDialogVisible=true
      this.updateMsgForm=row; 
    },
    //表格项删除函数
    async handleDelete(index, row) {
      console.log(row.id)
      console.log(typeof(row.id))
      let res=await studentApi.deleteStudent({"id":row.id});
      if(res.data.code==200){
        this.$message({
          message: '删除成功',
          type: 'success'
        });
        this.selectByPage();
      }else{
        this.$message.error('删除失败');
      }
    },
    //获取选中删除的表项数据
    handleSelectionChange(selection){
        this.deletedData=selection.map(item=>item.id)
        console.log(this.deletedData);
    },
    async deleteChecked(){
        if(this.deletedData.length==0){
            this.$message({
                type: 'warning',
                message: '请选择要删除的数据!'
            });
            return;
        }
        let res=await studentApi.deleteChecked(this.deletedData);
        if(res.data.code==200){
            this.$message({
                type:"success",
                message:res.data.msg
            })
        }
        this.selectByPage();
    },
    //重置查询表单
    resetSelectForm(){
      this.formInline = {
        stuId: '',
        stuName: '',
        stuAge:0,
        claScore:0
      };
      this.selectByPage()
    },
    //重置添加学生表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  }
}
</script>
<style scoped lang="less">
  *{
    box-sizing:border-box
  }
  #list{
    width:90%;
    margin: 0 auto;
  }
  h1{
    margin-bottom: 20px;
  }
  #list .table{
  }
  .el-pagination{
    margin : 20px;
  }
  .demo-form-inline{
    text-align: left;
    display: flex;
    justify-content: space-between;
  }
  .el-form--inline .el-form-item__content{
    width: 50% !important;
  }
</style>